// miniprogram/group_admin/pages/chapterPlayCourse/chapterPlayCourse.js
const api=require("../../../utils/api")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading:false,
    error:0,//页面状态
    videoFlag:0,//视频约定
    chapterFlag:0,//章节课约定
    evFlag:0,//评论约定
    state:false,//登录状态
    num:5,
    nav:2,//导航
    cover:"",//封面
    network_flag:false,//网络状态
    network_state:0,
    network:"",//网络状态
    network_title:"",//网络状态标题
    network_text:"",
    network_button_text:"",//网络状态处理标致
    type:-1,//模块
    id:'',//视频id
    videoInfo:{},//视频信息
    teacherId:-1,//教师id
    teacherInfo:{},//教师信息
    teacherEvList:[],//评价列表
    xing:{},//星星数量
    currentTime:0,//视频播放长度
    scrollTop:0,//当前播放距离顶部距离
    evScrollTop:0,
    selected:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    wx.showLoading({
      title: '加载中',
    })
    if(!this.verifyUser()){return ;}
    if(!this.verifyCourse()){return ;}
    this.setData({
      type:options.module,
      id:options.id,
      selected:JSON.parse(options.selected)
    })  
      //处理网络状态
    this.disposeNetwork();
      //监听网络变化
    this.onNetworkStatus();
    this.getData();
      //获取视频信息
    await this.getVideoData();
    //获取教师信息
    this.data.teacherId!=-1 ?  this.getTeacerInfo() : "";    


  },
  //获取章节课列表
  getData:async function(){
    const userdata=wx.getStorageSync('USERDATA');
    const courseinfo=wx.getStorageSync('COURSEINFO');
    const {sessionid,uid}=userdata;
    const courseid=courseinfo.id;
    const type=this.data.type;
    console.log("%c章节课","color:red;font-size:15px")
    const data=await api.sendPostsSync("/video/getvideolist",{sessionid,uid,courseid,type})
                        .catch((res)=>{return res;})
    // 请求成功
    if(data.errcode==0 && data.list.length>0){
      //课程列表
      this.setData({
        courses:data.list,
        error:1,
        scrollTop:(this.data.selected[0]+this.data.selected[1])*50
      })
    }
    setTimeout(()=>{
      wx.hideLoading()
    },2000)
  },
  //切换视频
  changePlayCourse:function(e){
    if(this.data.state&&this.data.currentTime!=0){
      this.submitVideoChange();
    }
    // var vid=e.currentTarget.dataset["vid"];
    this.setData({
      id:e.detail,
      currentTime:0
    })
    this.getVideoData();
  },
//---------------------------以下视频处理--------------------------------------
  getVideoData:async function(){
    const userdata=wx.getStorageSync('USERDATA');
    const courseinfo=wx.getStorageSync('COURSEINFO');
    const params={
      sessionid:userdata.sessionid,
      uid:userdata.uid,
      courseid:courseinfo.id,
      type:this.data.type,
      vid:this.data.id,
      definition:'ld'
    }
    console.log("%c视频信息","color:red;font-size:15px")
    const res=await api.sendPostsSync("/video/getvideocode",params)
                      .catch(res => res)
     if(parseInt(res.errcode)==40051){
      wx.hideLoading()
      this.setData({
        state:false
      })
      wx.showModal({
       title: '提示',
       content: '登录超时，请重新登录~',
       confirmText: "去登录",
       success (res) {
        wx.removeStorageSync("USERINFO");
        wx.removeStorageSync("USERDATA");
         if (res.confirm) {
           wx.reLaunch({
             url: '/pages/my/my',
           })
         }else if (res.cancel) {
           wx.navigateBack({
             delta: 1
           })
         }
       }
     })
     return;
   }
    if(!res.errcode){
      this.setData({
        videoInfo:res,
        teacherId:res.evaluationDetail.teacherid || -1
      })
      wx.setNavigationBarTitle({
        title: res.title,
      })
    }else{
      this.setData({
        network_flag:true,
        network_title:"视频加载失败~",
        network_button_text:"重新加载",
        network_state:2
      })
    }

    if(this.data.videoInfo=={}){
      this.setData({
        network_flag:true,
        network_title:"视频加载失败~",
        network_button_text:"重新加载",
        network_state:2
      })
    }
    
  },
  // 获取老师信息
  getTeacerInfo:async function(){
    const userdata=wx.getStorageSync('USERDATA');
    const params={
      sessionid:userdata.sessionid,
      uid:userdata.uid,
      teacherid:this.data.teacherId
    }
    console.log("%c教师信息","color:red;font-size:15px")
    const res=await api.sendPostsSync("/commodity/getTeacherEvaluation",params)
                        .catch(res => res)
    //   this.setData({
    //     evFlag:-1
    //   })
    if(!parseInt(res.errcode)&&res.xing>0){
      var xing={};
      xing.xing=res.xing;
      xing.xing1=parseFloat(res.xing1/res.xing).toFixed(2)*100;
      xing.xing2=parseFloat(res.xing2/res.xing).toFixed(2)*100;
      xing.xing3=parseFloat(res.xing3/res.xing).toFixed(2)*100;
      xing.xing4=parseFloat(res.xing4/res.xing).toFixed(2)*100;
      xing.xing5=parseFloat(res.xing5/res.xing).toFixed(2)*100;
      xing.avgXing=parseFloat(res.avgXing).toFixed(1);
      this.setData({
        teacherInfo:res,
        xing
      })
      this.getTeacerEvList();
     }
  },
  // 获取评价列表
  getTeacerEvList:async function(){
    const userdata=wx.getStorageSync('USERDATA');
    const courseinfo=wx.getStorageSync('COURSEINFO');
    const params={
      sessionid:userdata.sessionid,
      uid:userdata.uid,
      teacherid:this.data.teacherId,
      courseid:courseinfo.id,
      // pagesize:5,//每页数量
      // pagecurrent:1,//当前页
    }
    console.log("%c评价列表","color:red;font-size:15px");
    const res=await api.sendPostsSync("/knowPoint/getEvaluationList",params)
                        .catch(res=>res)
    if(!parseInt(res.errcode)){
      var list=[];
      var item=[];
      var flag=1;
      for(var i=0;i<res.list.length;){
        if(i<flag*5){
          item.push(res.list[i]);
          i++;
        }else{
          flag++;
          list.push(item);
          item=[];
        }
      }
      if(item!=[]){
        list.push(item);
      }
      this.setData({
        teacherEvList:list
      })
    }
  },
  evListScroll:function(e){
      this.setData({
        evScrollTop:306
      })
  },
  // 刷新网络状态
  refreshNetwork:function(e){
    const state=e.currentTarget.dataset.state;
    switch(parseInt(state) ){
      case 0:
        this.disposeNetwork();
        break;
      case 1:
        this.setData({
          network_flag:false
        })
        const videoContext=wx.createVideoContext("video", this);
        videoContext.play();
        break;
      case 2:
        this.getVideoData();
        break;
    }
  },
  // 处理网络状态
  disposeNetwork:function(){
    wx.getNetworkType({
      success:(res)=>{
        console.log("网络状态")
        console.log(res)
        this.setData({
          network:res.networkType
        })
        if(res.networkType!="none" && res.networkType!="wifi" && res.networkType!="unknown"){
          this.setData({
            network_flag:true,
            network_title:"本次播放需要消耗流量",
            network_text:"确认播放？",
            network_button_text:"播放",
            network_state:1,
          })
        }
        if(res.networkType=="none" || res.networkType=="unknown"){
          this.setData({
            network_flag:true,
            network_title:"网络未连接，请检查网络设置～",
            network_button_text:"刷新重试",
            network_state:0
          })
        }
        if(res.networkType=="wifi"){
          this.setData({
            network_flag:false
          })
        }
      }
    })
  },
  //监听网络状态
  onNetworkStatus:function(){
    wx.onNetworkStatusChange((res)=>{
      this.disposeNetwork();
    })
  },
  //切换导航
  changeNav:function(e){
    const index=e.currentTarget.dataset['index'];
    if(this.data.nav==parseInt(index)){
      return ;
    }
    switch (index) {
      case '1':
        this.setData({
        nav:1
        })
        break;
      case '2':
        this.setData({
          nav:2
        })
          break;
      case '3':
        this.setData({
          nav:3
        })
        break;
    }
  },
  //是否登录
  verifyUser:function(){
    const userdata=wx.getStorageSync('USERINFO');
    if(userdata){
      this.setData({
        state:true
      })
    }else{
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: '你还没登录哦~',
        confirmText: "去登录",
        success (res) {
          if (res.confirm) {
            wx.reLaunch({
              url: '/pages/my/my',
            })
          } else if (res.cancel) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
      return false;
    }
    return true;
  },
  verifyCourse:function(){
    const courseinfo=wx.getStorageSync('COURSEINFO');
    //判断是否选课
    if(!courseinfo){
      wx.hideLoading()
      wx.showModal({
        title: '提示',
        content: '请先选择课程~',
        confirmText: "去选择",
        success (res) {
          if (res.confirm) {
            wx.reLaunch({
              url: '/group_admin/pages/subject/subject',
            })
          } else if (res.cancel) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
      return false;
    }
    return true;
  },
  //视频进度改变
  videoPlayChange:function(e){
    const currentTime=e.detail.currentTime;
    this.setData({
      currentTime
    })
  },
  //上传视频进度
  submitVideoChange:async function(){
    const userdata=wx.getStorageSync('USERDATA');
    const courseinfo=wx.getStorageSync('COURSEINFO');
    const params={
      uid:userdata.uid,
      sessionid:userdata.sessionid,
      courseid:courseinfo.id,
      type:this.data.type,
      code:this.data.id,
      lastposition:this.data.currentTime
    }
    console.log("%c视频进度提交","color:red;font-size:15px")
    const res = await api.sendPostsSync("/video/setLastPlayPosition",params)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if(this.data.state&&this.data.currentTime!=0){
      this.submitVideoChange();
    }
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if(this.data.state&&this.data.currentTime!=0){
      this.submitVideoChange();
    }
    if(this.data.videoInfo.isEvaluation=='0'){
        wx.showModal({
          title: '课程评价',
          content: '您的客观评价可以提高老师授课技能和课程质量',
          confirmText: '立即评价',
          confirmColor: '#FECD31',
          cancelText: '下次再说',
          success:  (res)=> {
            if (res.confirm) {
              wx.navigateTo({
                url: `/group_admin/pages/chapterEvaluate/chapterEvaluate?type=${this.data.type}&vid=${this.data.id}`
              })
            } else {
              
            }

          }
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})